package com.example.werewolf.service.impl.role;

import com.alibaba.fastjson2.JSONObject;
import com.example.werewolf.common.ActionType;
import com.example.werewolf.entity.Event;
import com.example.werewolf.entity.GamePhase;
import com.example.werewolf.entity.Player;
import com.example.werewolf.model.ActionSkill;
import com.example.werewolf.model.GameChatResp;
import com.example.werewolf.service.ActionStrategy;
import com.example.werewolf.utils.PrintUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class VotingActionStrategy implements ActionStrategy {

    @Override
    public ActionSkill execute(List<Player> players, List<Player> actionPlayers,
                               GamePhase phase, List<Event> publicEvents, SseEmitter emitter) throws IOException {
        System.out.println("🗳️ 投票阶段开始，每人独立投票，不可交流...");
        Map<Integer, Integer> voteCount = new HashMap<>();

        for (Player player : actionPlayers) {
            // ✅ 每个玩家独立发言，AI 不知道别人怎么投（因为没有上下文传递）
            String chat = player.chat("请投票选出你认为是狼人的玩家，直接输出编号，如：3。弃权请输出 -1。");
            GameChatResp resp = parseResponse(chat);

            PrintUtils.printPlayer(emitter, player, resp.getContent());

            if (resp != null && resp.getTargetNum() >= -1) { // 允许 -1 弃权
                voteCount.put(resp.getTargetNum(), voteCount.getOrDefault(resp.getTargetNum(), 0) + 1);
            }
        }

        // 找出得票最多者（允许平票）
        Integer maxTarget = voteCount.entrySet().stream()
                .max(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElse(-1);

        String sout = "📊 投票结果：" + voteCount + "，最高票目标：" + maxTarget;
        System.out.println(sout);

        // action
        PrintUtils.printSystem(emitter, sout);
        return ActionSkill.builder()
                .actionType(ActionType.EXILE_VOTE)
//                .maxTarget
                .build();
    }

    private GameChatResp parseResponse(String json) {
        try {
            return JSONObject.parseObject(json, GameChatResp.class);
        } catch (Exception e) {
            System.err.println("解析投票响应失败: " + e.getMessage());
            return null;
        }
    }
}